package com.gouqi.tools.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.gouqi.gouqitoolsclientsdk.client.GouqiToolClient;
import com.gouqi.gouqitoolscommon.model.entity.Tool;
import com.gouqi.gouqitoolscommon.model.entity.User;
import com.gouqi.tools.common.*;
import com.gouqi.tools.exception.BusinessException;
import com.gouqi.tools.exception.ThrowUtils;
import com.gouqi.tools.model.dto.tool.*;
import com.gouqi.tools.model.enums.ToolStatusEnum;
import com.gouqi.tools.model.vo.ToolVO;
import com.gouqi.tools.service.ToolService;
import com.gouqi.tools.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 工具接口
 */
@RestController
@RequestMapping("/tool")
@Slf4j
public class ToolController {

    private final static Gson GSON = new Gson();
    @Resource
    private ToolService toolService;
    @Resource
    private UserService userService;

    @Resource
    private GouqiToolClient gouqiToolClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param toolAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addTool(@RequestBody ToolAddRequest toolAddRequest, HttpServletRequest request) {
        if (toolAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tool tool = new Tool();
        BeanUtils.copyProperties(toolAddRequest, tool);
        toolService.validTool(tool, true);
        User loginUser = userService.getLoginUser(request);
        //todo 修改用户id的类型
        tool.setUserId(loginUser.getId().toString());
        boolean result = toolService.save(tool);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        String newToolId = tool.getId();
        return ResultUtils.success(newToolId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTool(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        String id = deleteRequest.getId();
        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        ThrowUtils.throwIf(oldTool == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldTool.getUserId().equals(user.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = toolService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param toolUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTool(@RequestBody ToolUpdateRequest toolUpdateRequest, HttpServletRequest request) {
        if (toolUpdateRequest == null || toolUpdateRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tool tool = new Tool();
        BeanUtils.copyProperties(toolUpdateRequest, tool);
        List<String> tags = toolUpdateRequest.getTags();
        tool.setTags(JSONUtil.toJsonStr(tags));
        // 参数校验
        toolService.validTool(tool, false);
        User user = userService.getLoginUser(request);

        String id = toolUpdateRequest.getId();
        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        ThrowUtils.throwIf(oldTool == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可修改
        if (!oldTool.getUserId().equals(user.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = toolService.updateById(tool);
        return ResultUtils.success(result);
    }

    /**
     * 发布
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineTool(@RequestBody IdRequest idRequest,
                                            HttpServletRequest request) {
        if (idRequest == null || idRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String id = idRequest.getId();
        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        if (oldTool == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

//        com.gouqi.gouqitoolsclientsdk.model.User user = new com.gouqi.gouqitoolsclientsdk.model.User();
//        user.setName("gouqi");
//        String userName = gouqiToolClient.getUserNameByPost(user);
//        if (StringUtils.isBlank(userName)) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
//        }
        Tool tool = new Tool();
        tool.setId(id);
        tool.setStatus(ToolStatusEnum.ONLINE.getValue());
        boolean result = toolService.updateById(tool);
        return ResultUtils.success(result);
    }

    /**
     * 下线
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineTool(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        if (idRequest == null || idRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String id = idRequest.getId();
        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        if (oldTool == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

//        com.gouqi.gouqitoolsclientsdk.model.User user = new com.gouqi.gouqitoolsclientsdk.model.User();
//        user.setName("gouqi");
//        String userName = gouqiToolClient.getUserNameByPost(user);
//        if (StringUtils.isBlank(userName)) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
//        }
        Tool tool = new Tool();
        tool.setId(id);
        tool.setStatus(ToolStatusEnum.OFFLINE.getValue());
        boolean result = toolService.updateById(tool);
        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     *
     * @param toolInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeTool(@RequestBody ToolInvokeRequest toolInvokeRequest, HttpServletRequest request) {
        if (toolInvokeRequest == null || toolInvokeRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String id = toolInvokeRequest.getId();
        String userRequestParams = toolInvokeRequest.getUserRequestParams();

        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        if (oldTool == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        if (oldTool.getStatus() == ToolStatusEnum.OFFLINE.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");
        }
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        Gson gson = new Gson();
        GouqiToolClient gouqiToolClient = new GouqiToolClient(accessKey, secretKey);
        com.gouqi.gouqitoolsclientsdk.model.User user = gson.fromJson(userRequestParams, com.gouqi.gouqitoolsclientsdk.model.User.class);
        String userNameByPost = gouqiToolClient.getUserNameByPost(user);
        return ResultUtils.success(userNameByPost);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ToolVO> getToolVOById(@RequestParam String id, HttpServletRequest request) {
        if (id.length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tool tool = toolService.getById(id);
        if (tool == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(toolService.getToolVO(tool, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param toolQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ToolVO>> listToolVOByPage(@RequestBody ToolQueryRequest toolQueryRequest,
                                                       HttpServletRequest request) {
        long current = toolQueryRequest.getCurrent();
        long size = toolQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Tool> toolPage = toolService.page(new Page<>(current, size),
                toolService.getQueryWrapper(toolQueryRequest));
        return ResultUtils.success(toolService.getToolVOPage(toolPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param toolQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ToolVO>> listMyToolVOByPage(@RequestBody ToolQueryRequest toolQueryRequest,
                                                         HttpServletRequest request) {
        if (toolQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        toolQueryRequest.setUserId(loginUser.getId());
        long current = toolQueryRequest.getCurrent();
        long size = toolQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Tool> toolPage = toolService.page(new Page<>(current, size),
                toolService.getQueryWrapper(toolQueryRequest));
        return ResultUtils.success(toolService.getToolVOPage(toolPage, request));
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param toolEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTool(@RequestBody ToolEditRequest toolEditRequest, HttpServletRequest request) {
        if (toolEditRequest == null || toolEditRequest.getId().length() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tool tool = new Tool();
        BeanUtils.copyProperties(toolEditRequest, tool);
        // 参数校验
        toolService.validTool(tool, false);
        User loginUser = userService.getLoginUser(request);
        String id = toolEditRequest.getId();
        // 判断是否存在
        Tool oldTool = toolService.getById(id);
        ThrowUtils.throwIf(oldTool == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTool.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = toolService.updateById(tool);
        return ResultUtils.success(result);
    }

}
